import dayjs from 'dayjs'
import routers from '@/router/staticModules/mobile'
import { jsonToSheetXlsx } from '@/components/Excel'
import type { App, Plugin } from 'vue'
/**
 * @description 处理首字母大写 abc => Abc
 * @param str
 */
export const changeStr = (str: string) => {
  return str.charAt(0).toUpperCase() + str.slice(1)
}

/**
 * @description 随机生成颜色
 * @param {string} type
 * @return {string}
 */
export const randomColor = (type: 'rgb' | 'hex' | 'hsl'): string => {
  switch (type) {
    case 'rgb':
      return window.crypto.getRandomValues(new Uint8Array(3)).toString()
    case 'hex':
      return (
        '#' +
        Math.floor(Math.random() * 0xffffff)
          .toString(16)
          .padStart(6, `${Math.random() * 10}`)
      )
    case 'hsl':
      // 在25-95%范围内具有饱和度，在85-95%范围内具有亮度
      return [360 * Math.random(), 100 * Math.random() + '%', 100 * Math.random() + '%'].toString()
  }
}

/**
 * 复制文本
 * @param text
 */
export const copyText = (text: string) => {
  return new Promise((resolve, reject) => {
    const copyInput = document.createElement('input') //创建一个input框获取需要复制的文本内容
    copyInput.value = text
    document.body.appendChild(copyInput)
    copyInput.select()
    document.execCommand('copy')
    copyInput.remove()
    resolve(true)
  })
}

/**
 * @description 判断字符串是否是base64
 * @param {string} str
 */
export const isBase64 = (str: string): boolean => {
  if (str === '' || str.trim() === '') {
    return false
  }
  try {
    return btoa(atob(str)) == str
  } catch (err) {
    return false
  }
}
// 对象转JSON
export const toJSON = (obj) => {
  return JSON.stringify(obj, (key, value) => {
    switch (true) {
      case typeof value === 'undefined':
        return 'undefined'
      case typeof value === 'symbol':
        return value.toString()
      case typeof value === 'function':
        return value.toString()
      default:
        break
    }
    return value
  })
}

/***
 * @description 是否是生产环境
 */
export const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV!)
export const IS_DEV = ['development'].includes(process.env.NODE_ENV!)

/***
 * @description 格式化日期
 * @param time
 */
export const formatDate = (time = +new Date()) => dayjs(time).format('YYYY-MM-DD HH:mm:ss')

/**
 *  @description 将一维数组转成树形结构数据
 * @param items
 * @param id
 * @param link
 */
export const generateTree = (items, id = 0, link = 'parent') => {
  return items
    .filter((item) => item[link] == id)
    .map((item) => ({
      ...item,
      slots: { title: 'name' },
      children: generateTree(items, item.departmentid)
    }))
}

/***
 * @description 原生加密明文
 * @param {string} plaintext
 */
const encryption = (plaintext: string) =>
  isBase64(plaintext) ? plaintext : window.btoa(window.encodeURIComponent(plaintext))

/**
 * @description 原生解密
 * @param {string} ciphertext
 */
const decryption = (ciphertext: string) =>
  isBase64(ciphertext) ? window.decodeURIComponent(window.atob(ciphertext)) : ciphertext

/**
 * / _ - 转换成驼峰并将view替换成空字符串
 * @param {*} name name
 */
export const toHump = (name) => {
  return name
    .replace(/[\-\/\_](\w)/g, (all, letter) => {
      return letter.toUpperCase()
    })
    .replace('views', '')
}

export const getIsMobile = () => {
  return /phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone|webOS|android/i.test(
    navigator.userAgent
  )
}
export const mobileRouterWhite = () => {
  const routerArr: any = []
  routers.map((item: any) => {
    if (!item.meta.hasLogin) {
      routerArr.push(item.name)
    }
  })
  return routerArr
}
export const getBase64 = (img: Blob, callback: (base64Url: string) => void) => {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result as string))
  reader.readAsDataURL(img)
}

export const banShare = () => {
  function onBridgeReady() {
    //@ts-ignore
    WeixinJSBridge.call('hideOptionMenu')
  }
  //@ts-ignore
  if (typeof WeixinJSBridge == 'undefined') {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
      //@ts-ignore
    } else if (document.attachEvent) {
      //@ts-ignore
      document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
      //@ts-ignore
      document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
    }
  } else {
    onBridgeReady()
  }
}

export const getMonthStart = () => {
  const date = new Date()
  date.setDate(1)
  let month: any = date.getMonth() + 1
  let day: any = date.getDate()
  if (month < 10) {
    month = '0' + month
  }
  if (day < 10) {
    day = '0' + day
  }
  return date.getFullYear() + '-' + month + '-' + day
}
export const getMonthEnd = () => {
  const endDate = new Date()
  let currentMonth = endDate.getMonth()
  const nextMonth = ++currentMonth
  const nextMonthFirstDay: any = new Date(endDate.getFullYear(), nextMonth, 1)
  const oneDay = 1000 * 60 * 60 * 24
  const lastTime = new Date(nextMonthFirstDay - oneDay)
  let endMonth: any = lastTime.getMonth() + 1
  let endDay: any = lastTime.getDate()
  if (endMonth < 10) {
    endMonth = '0' + endMonth
  }
  if (endDay < 10) {
    endDay = '0' + endDay
  }
  return endDate.getFullYear() + '-' + endMonth + '-' + endDay
}
//获取当天的开始时间和结束时间
export const getDayTime = (time = +new Date()) => {
  const nowTimeDate = new Date(time)
  return [
    formatDate(nowTimeDate.setHours(0, 0, 0, 0)),
    formatDate(nowTimeDate.setHours(23, 59, 59, 999))
  ]
}
//获取当天的开始时间和结束时间
export const isWx = () => {
  const ua = navigator.userAgent.toLowerCase()
  // @ts-ignore
  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    console.log('微信环境')
    return true
  } else {
    console.log('不是微信环境')
    return false
  }
}

export const withInstall = <T>(component: T, alias?: string) => {
  const comp = component as any
  comp.install = (app: App) => {
    app.component(comp.name || comp.displayName, component)
    if (alias) {
      app.config.globalProperties[alias] = component
    }
  }
  return component as T & Plugin
}

